/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package eu.ict_omelette.mashup.adapters.pipes.database.loader;

import eu.ict_omelette.mashup.adapters.pipes.Canonical2Json;
import eu.ict_omelette.mashup.adapters.pipes.KindOfFile;
import eu.ict_omelette.mashup.canonicalmodel.CanonicalMashup;
import eu.ict_omelette.mashup.canonicalmodel.Component;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URI;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author guybrush
 */
public class ParamValueKnowledgeLoader {

    static final String create = "create table if not exists ParameterValues " +
        "(componentName varchar(100), conf text, desc varchar(1000), usage int(20) DEFAULT (1), date Timestamp, "
        + "UpVotes int(20) DEFAULT (0), DownVotes int(20) DEFAULT (0), Tags varchar(256), "
        + "primary key(componentName, conf) ) ",
                        insert = "INSERT INTO ParameterValues (componentName, conf, usage) VALUES ",
                        update = "UPDATE ParameterValues SET usage = ",
                        usage = "SELECT usage FROM ParameterValues ";
    private KindOfFile kof = null;

    public KindOfFile getKindOfFile() { return kof; }
    public void setKindOfFile(KindOfFile kof) { this.kof = kof; }

    public ParamValueKnowledgeLoader(KindOfFile kof) { this.kof = kof; }

    public void LoadFolder(String path) throws SQLException
    {
        String[] children = new File(path).list();

        if(children == null || children.length < 1)
        { System.out.println("Directory does not exists or it is empty"); System.exit(1); }

        for(int i = 0; i < children.length; i++)
            LoadFile(path + "/" +children[i]);
    }
    public void LoadFile(URI uri) throws SQLException { LoadFile(uri.getPath()); }
    public void LoadFile(String filepath) throws SQLException
    {
        Connection conn = null;
        Statement stat = null;

        try{
            Class.forName("org.sqlite.JDBC");
            conn = DriverManager.getConnection("jdbc:sqlite:bayatest.sqlite");
            stat = conn.createStatement();
            stat.execute(create);

            CanonicalMashup cm = new Canonical2Json(kof, filepath).getCanonicalMashup();

            for (Iterator<Component> it = cm.getComponents(); it.hasNext();) {
                Component comp = it.next();
                String comp_tp = comp.getType(),
                       comp_conf = Canonical2Json.getConfOfComp(comp);

                if (!comp_tp.equals("output"))
                {
                    Integer usage = getUsage(stat, comp_tp, comp_conf);

                    if (usage < 1) addRow(stat, comp_tp, comp_conf);
                    else setUsage(stat, comp_tp, comp_conf, usage + 1);
                }
            }
        }catch(Exception e){ System.out.println(e.getMessage() + " in file: " + filepath); }
        finally
        {
            if (stat != null) stat.close();
            if (conn != null) conn.close();
        }
    }

    static private String getDefWhereStmt(String comp, String conf)
    { return " WHERE componentName = '" + comp.replaceAll("'", "&#039;") + "' AND conf = '" + conf.replaceAll("'", "&#039;") + "'"; }
    static private void addRow(Statement stmt, String comp, String conf) throws SQLException
    { if (conf.length() > 11) stmt.execute(insert + "('" + comp.replaceAll("'", "&#039;") + "','" + conf.replaceAll("'", "&#039;") + "',1)"); }
    static private void incUsage(Statement stmt, String comp, String conf) throws SQLException
    { setUsage(stmt, comp, conf, (getUsage(stmt, comp, conf) + 1)); }
    static private void setUsage(Statement stmt, String comp, String conf, Integer usage) throws SQLException
    { stmt.executeUpdate(update + "'" + String.valueOf(usage) + "'" + getDefWhereStmt(comp, conf)); }
    static private Integer getUsage(Statement stmt, String comp, String conf) throws SQLException
    { ResultSet res = stmt.executeQuery(usage + getDefWhereStmt(comp, conf)); if (res.next()) return res.getInt(1); return 0; }
}
